/*
 * @Author: C.
 * @Date: 2023-04-06 14:42:26
 */
import { handleRouteName, handleCURDName } from '../utils';
import { buildUUID } from '/@/utils/uuid';
export interface IMenu {
  name: string;
  title: string;
  children?: IMenu[] | null;
}
export interface IMenuTree {
  menuList: IMenu[] | null;
  parentPath?: string;
  level?: number;
  isShortName?: boolean;
}
/**
 * @description: 补充生成菜单树
 * @return {*}
 */
export function genMenuTree({
  menuList = [],
  parentPath = '/work',
  level = 0,
  isShortName = false,
}: IMenuTree): Recordable[] | null {
  if (!menuList || menuList.length == 0) return null;
  return menuList.map((item) => {
    const path = isShortName ? handleCURDName(item.name) : handleRouteName(item.name);
    const realPath = `${parentPath}/${path}`;
    return {
      path: `${level == 0 ? '/' : ''}${path}`,
      component: level == 0 ? 'LAYOUT' : realPath + '/index',
      type: level == 0 ? '0' : '1',
      status: '0',
      hideMenu: false,
      ignoreKeepAlive: false,
      hideChildrenInMenu: false,
      hideTab: false,
      hidePathForChildren: false,
      affix: false,
      ...item,
      title: isShortName ? item.title : `routes.menu.${item.name}`,
      children: item.children
        ? genMenuTree({
            menuList: item.children,
            parentPath: realPath,
            level: ++level,
          })
        : genMenuTree({
            menuList: genCURDMenu(item),
            parentPath: realPath,
            level: ++level,
            isShortName: true,
          }),
    };
  });
}
// 辅助生成编辑和详情页面
function genCURDMenu(menu): IMenu[] | null {
  if (!menu.isCURD) return null;
  const curd = [
    {
      title: '编辑',
      name: '_Edit',
    },
    {
      title: '详情',
      name: '_Detail',
    },
  ];
  return curd.map((item) => {
    return {
      name: `${menu.name}${item.name}`,
      title: `${menu.title}${item.title}`,
      children: null,
      hideMenu: true,
    };
  });
}
// 将树形菜单转换成集合
export function genMenuMap(params: IMenuTree) {
  const menuList = genMenuTree(params);
  const stack: any[] = [];
  function handleTree(treeMap, parentMenu = '') {
    const currentObj = {
      ...treeMap,
      children: null,
      parentMenu,
      id: buildUUID(),
    };
    stack.push(currentObj);
    treeMap.children && handleChild(treeMap.children, currentObj.id);
  }

  function handleChild(list = [], parentMenu = '') {
    list.forEach((item) => {
      handleTree(item, parentMenu);
    });
  }
  menuList &&
    menuList.forEach((item) => {
      handleTree(item);
    });
  return stack;
}
